package com.thinker.mq;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends Thread {

	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(5678);
		while (true) {
			Server mc = new Server(server.accept());
			mc.start();
		}
	}

	private final Socket client;

	public Server(Socket c) {
		this.client = c;
	}

	public Socket getClient() {
		return client;
	}

	@Override
	public void run() {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
			PrintWriter out = new PrintWriter(client.getOutputStream());
			while (true) {
				String str = in.readLine();
				if (str.contains("code:200")) {
					JmsBuffer.produce(str);
				}
				if (str.contains("code:400")) {
					String msg = JmsBuffer.consume();
					out.println(msg);
					out.flush();
				}
				System.out.println(str);
				out.flush();
				if (str.equals("end")) {
					break;
				}
			}
			client.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
